import { useUserStore } from '@/stores/user'
import type { Directive, DirectiveBinding } from 'vue'

/**
 * 权限指令
 * 使用方式：v-permission="'system:user:add'" 或 v-permission="['system:user:add', 'system:user:edit']"
 */
export const permission: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()

    if (value) {
      const hasPermission = userStore.hasPermission(value)
      if (!hasPermission) {
        // 没有权限，移除元素
        el.parentNode?.removeChild(el)
      }
    } else {
      throw new Error('需要传入权限标识！如 v-permission="\'system:user:add\'"')
    }
  }
}

/**
 * 权限指令（隐藏模式）
 * 使用方式：v-permission-hide="'system:user:add'"
 * 没有权限时隐藏元素而不是移除
 */
export const permissionHide: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value } = binding
    const userStore = useUserStore()

    if (value) {
      const hasPermission = userStore.hasPermission(value)
      if (!hasPermission) {
        el.style.display = 'none'
      }
    }
  }
}

export default {
  permission,
  permissionHide
}
